from rest_framework import serializers
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.settings import api_settings

from .models import Role, Permission, Account


class AccountSerializer(serializers.ModelSerializer):
    """ 用户的序列化类 """
    created_time = serializers.DateTimeField(format="%Y-%m-%d", required=False, read_only=True)
    password = serializers.CharField(write_only=True)

    def validate_is_superuser(self, value):
        print(value)
        # 创建超级管理员的账号时，需要判断请求的用户是否为超级管理员，只有超级管理员才能创建超级管理员账号
        if value is True and self.context.get('request_user_is_superuser', False) is True:
            return value
        raise serializers.ValidationError(detail="只有超级管理员才能创建超级管理员账号")

    def create(self, validated_data):
        account = Account(**validated_data)
        account.set_password(validated_data['password'])
        account.origin_password = validated_data['password']
        account.save()
        return account

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        # role_name_lst = set([role.name for role in instance.roles.all() if role.display])
        # if instance.group == 'Teacher':
        #     role_name_lst.add('教师')
        # if instance.group == 'Student':
        #     role_name_lst.add('学生')
        # ret['roles_name'] = ', '.join(role_name_lst)
        return ret

    class Meta:
        model = Account
        fields = ['id', 'username', 'password', 'telephone', 'is_active', 'created_time',
                  'last_login', 'roles', 'realname', 'is_superuser']
        read_only_fields = ('id', 'created_time', 'last_login', 'roles')


class AccountUpdateSerializer(serializers.ModelSerializer):
    """ 用户的序列化类 """
    created_time = serializers.DateTimeField(format="%Y-%m-%d", required=False, read_only=True)
    is_superuser = serializers.BooleanField()

    def validate_is_superuser(self, value):
        # 请求的用户为超级管理员，才能设置超级管理员字段
        if self.context.get('request_user_is_superuser', False) is True:
            return value
        raise serializers.ValidationError(detail="只有超级管理员才能设置超级管理员")

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        role_name_lst = set([role.name for role in instance.roles.all() if role.display])
        if instance.group == 'Teacher':
            role_name_lst.add('教师')
        if instance.group == 'Student':
            role_name_lst.add('学生')
        ret['roles_name'] = ', '.join(role_name_lst)
        return ret

    class Meta:
        model = Account
        fields = ['id', 'username', 'telephone', 'is_active', 'created_time',
                  'last_login', 'roles', 'realname', 'is_superuser']
        read_only_fields = ('id', 'created_time', 'last_login', 'roles')


class RoleListSerializer(serializers.ModelSerializer):
    """
        角色的序列化类
    """
    class Meta:
        model = Role
        # fields = ('id', 'name', 'codename', 'permissions', 'parent', 'desc', 'can_set_people')
        fields = '__all__'
        read_only_fields = ('permissions', 'can_set_people')

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        account_qs = instance.user_set.all()   # 该角色的所有人员信息
        ret['person'] = [i.id for i in account_qs]
        person_name_lst = [f"{i.realname}" for i in account_qs]
        ret['person_name'] = ', '.join(person_name_lst)
        ret['account_list'] = [{'id': i.id, 'username': i.username, 'realname': i.realname} for i in account_qs]
        ret['child'] = []
        return ret


class RoleCreateSerializer(serializers.ModelSerializer):
    """
        角色的序列化类
    """
    class Meta:
        model = Role
        fields = ('id', 'name', 'codename')

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        ret['child'] = []
        return ret


class PermsListSerializer(serializers.ModelSerializer):
    """
        权限的序列化类
    """
    class Meta:
        model = Permission
        fields = '__all__'


class CustomTokenRefreshSerializer(serializers.Serializer):
    """
    自定义刷新token返回的数据
    """
    refresh = serializers.CharField()

    def validate(self, attrs):
        refresh = RefreshToken(attrs['refresh'])

        data = {'token': str(refresh.access_token)}

        if api_settings.ROTATE_REFRESH_TOKENS:
            if api_settings.BLACKLIST_AFTER_ROTATION:
                try:
                    # Attempt to blacklist the given refresh token
                    refresh.blacklist()
                except AttributeError:
                    # If blacklist app not installed, `blacklist` method will
                    # not be present
                    pass

            refresh.set_jti()
            refresh.set_exp()

            data['refresh'] = str(refresh)

        return data


class TeacherSerializer(serializers.ModelSerializer):

    class Meta:
        model = Account
        fields = ['id', 'username', 'realname']
